import QtQuick 2.0
import QtQuick.Window 2.12
import QtQuick.Controls 2.15
import './test.js' as Jie

Window {
    id: window
    width: 640
    height: 480
    visible: true

    Item {
        id: jieItem
        anchors.fill: parent

        //通过js返回颜色，实现颜色的生成全在函数中实现，只要传入生成rgb颜色的函数即可
        property var colorBuilder: Jie.getColorFactory(Qt.rgba)

        ListView {
            id: jieList
            anchors.fill: parent
            model: ListModel {
                id: jieListModel
                ListElement {
                    name: '张三'
                    group: 'student'
                    age: 33
                }
                ListElement {
                    name: '李四'
                    group: 'student'
                    age: 23
                }
                ListElement {
                    name: '晨晨'
                    group: 'teacher'
                    age: 23
                }
                ListElement {
                    name: '周六'
                    group: 'student'
                    age: 23
                }
            }
            delegate: Rectangle {
                width: jieList.width
                height: jieList.height/10

                color: jieItem.colorBuilder()
                Text {
                    anchors.fill: parent
                    text: name + ' ' + age + (parent.isCurrentIndex() ? ' √' : '')
                    font.pointSize: 16

                    //使用居中的时候一定要设置父对象的宽高，父对象宽高不能使用锚点
                    verticalAlignment: Text.AlignVCenter
                    horizontalAlignment: Text.AlignHCenter
                }

                MouseArea {
                    anchors.fill: parent
                    onClicked: {
                        console.log('index:' + index)
                        let data = jieListModel.get(index)
                        console.log(JSON.stringify(data))
                        parent.setCurrentIndex()
                    }
                }

                function setCurrentIndex() {
                    jieList.currentIndex = index
                }

                function isCurrentIndex() {
                    return jieList.currentIndex === index
                }
            }

            Component.onCompleted: {
                //此处能直接加直接绑定，和上面一课时的model不一样
                jieList.model.append({'name': '米敏', 'group': 'teacher', 'age': 44})
            }
        }
    }
}
